package com.android.samples.mediastore.hms.drive

import android.os.Bundle
import android.util.Log
import android.view.*
import android.widget.ImageView
import androidx.activity.result.IntentSenderRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.android.samples.mediastore.R
import com.android.samples.mediastore.databinding.ActivityDriveBinding
import com.android.samples.mediastore.databinding.DialogOperateBinding
import com.android.samples.mediastore.hms.drive.base.BaseActivity
import com.android.samples.mediastore.hms.drive.utils.HmsSigninUtils
import com.android.samples.mediastore.hms.drive.utils.MimeType
import com.bumptech.glide.Glide
import com.bumptech.glide.load.model.GlideUrl
import com.huawei.cloud.services.drive.model.File
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.*
import java.util.*

@AndroidEntryPoint
class DriveActivity : BaseActivity<ActivityDriveBinding>() {
    private val TAG = "DriveActivity"
    private val driveViewModel by viewModels<DriveViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        driveViewModel.textLiveData.observe(this) {
            binding.userInfo.text = it
        }
        driveViewModel.getUserInformation()
        folderStack.push("root")
        driveViewModel.loadPicturesFromRoot()
        val driverAdapter = DriverAdapter {
            if (it.mimeType == MimeType.FOLDER) {
                Log.d(TAG, "点击  目录:  ${it.fileName}")
                folderStack.push(it.id)
                driveViewModel.loadPicturesFromFolder(it.id)
            } else {
                Log.d(TAG, "点击  文件:  ${it.fileName}")
                OperateDialog(it).show(supportFragmentManager, "sss")
            }
        }
        binding.recyclerView.run {
            adapter = driverAdapter
            layoutManager = GridLayoutManager(this@DriveActivity, 3)
        }

        driveViewModel.filesLiveData.observe(this) { list ->
            Log.d(TAG, "observe: " + list!!.size)
            if (list.isNotEmpty()) {
                driverAdapter.submitList(list)
            }

        }
    }

    private val folderStack = Stack<String>()
    override fun onBackPressed() {
        if (folderStack.empty() || folderStack.peek() == "root") {
            super.onBackPressed()
        } else {
            folderStack.pop()
            driveViewModel.loadPicturesFromFolder(folderStack.peek())
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.drive, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
//            R.id.createDir -> driveViewModel.createDirectoryTest()
//            R.id.query -> queryTest()
            R.id.createFiles -> driveViewModel.createFileTest()
//            R.id.copy -> copyTest()
//            R.id.update_file -> updateFileTest()
//            R.id.modify_file -> modifyFileTest()
//            R.id.delete -> deleteTest()
//            R.id.getFileMetadata -> getFileMetadataTest()
//            R.id.downLoadFile -> downLoadFileTest()
//            R.id.filesWatch -> filesWatchTest()
//
//            R.id.doBackUpData -> doBackUpDataTest()
//            R.id.doRestoreData -> doRestoreData()

        }
        return super.onOptionsItemSelected(item)
    }


    private inner class DriverAdapter(val onClick: (File) -> Unit) :
        ListAdapter<File, ImageViewHolder>(DiffCallback) {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ImageViewHolder {
            val layoutInflater = LayoutInflater.from(parent.context)
            val view = layoutInflater.inflate(R.layout.gallery_layout, parent, false)
            return ImageViewHolder(view, onClick)
        }


        override fun onBindViewHolder(holder: ImageViewHolder, position: Int) {
            val image = getItem(position)
            holder.rootView.tag = image
            if (image.mimeType == MimeType.FOLDER) {
                Glide.with(holder.imageView)
                    .load(R.drawable.ic_baseline_folder_24)
                    .thumbnail(0.33f)
                    .centerCrop()
                    .into(holder.imageView)
            } else {
                val glideUrl = GlideUrl(image.smallThumbnailDownloadLink, HmsSigninUtils.headers)
                Glide.with(holder.imageView)
                    .load(glideUrl)
                    .thumbnail(0.33f)
                    .centerCrop()
                    .into(holder.imageView)
            }
        }

    }

    class OperateDialog(private val file: File) : DialogFragment() {
        lateinit var binding: DialogOperateBinding

        private val driveViewModel by lazy { ViewModelProvider(requireActivity()).get(DriveViewModel::class.java) }


        override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View {
            binding = DialogOperateBinding.inflate(inflater, container, false)
            return binding.root
        }

        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)

            with(binding) {
                delete.setOnClickListener {
                    driveViewModel.delete(file)
                    dismiss()
                }
                download.setOnClickListener {
                    driveViewModel.download(file)
                    dismiss()
                }
            }

        }

        override fun onStart() {
            super.onStart()
            dialog?.window?.setBackgroundDrawableResource(android.R.color.transparent)
        }
    }
}


private class ImageViewHolder(view: View, onClick: (File) -> Unit) : RecyclerView.ViewHolder(view) {
    val rootView = view
    val imageView: ImageView = view.findViewById(R.id.image)

    init {
        imageView.setOnClickListener {
            val image = rootView.tag as? File?
            image?.let(onClick)
        }
    }
}


private val DiffCallback = object : DiffUtil.ItemCallback<File>() {
    override fun areItemsTheSame(oldItem: File, newItem: File): Boolean {
        return oldItem.id == newItem.id
    }

    override fun areContentsTheSame(oldItem: File, newItem: File): Boolean {
        return oldItem == newItem
    }

}